import * as React from 'react'
import { Table, Input, Button, Space, Form, InputNumber, message, Popconfirm, Row, Divider, Col, Card } from 'antd';
import { SearchOutlined, ReloadOutlined, EditOutlined, DeleteOutlined, PlayCircleOutlined } from '@ant-design/icons';
import MyModal from '../notification-table/my-modal';


export interface PickingProps {
    name?: string;
    searchKeys?: string;
    getMainDataUrl?: string;
    getSubDataUrl?: string;
    postMainDataUrl?: string;
    postSubDataUrl?: string;
    putMainDataUrl?: string;
    actUrl?: string;
}


const Picking: React.FC<PickingProps> = function ({ name, searchKeys,
    getMainDataUrl, getSubDataUrl, postMainDataUrl, postSubDataUrl, putMainDataUrl, actUrl,
    ...otherProps }) {

    // function get(url){
    //     fetch(url)
    //     .then(response => response.json())
    //     .then(data => {
    //     })

    //     fetch(putUrl, {
    //         method: 'PUT',
    //         headers: {
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify(
    //            row
    //         )
    //     })
    //     .then(response => response.json())
    //     .then(data => {if(data.code === '0'){
    //       messageApi.open({
    //         type: 'success',
    //         content: '修改成功',
    //       });
    //     }})
    // }

    const [searchTerm, setSearchTerm] = React.useState({});
    const [messageApi, contextHolder] = message.useMessage();
    const defaultMainData = [
        {
            
            "note": "",
            "params": {},
            "id": 9,
            "code": "ISSUE20250412006",
            "name": "221122",
            "workstationId": 1,
            "workstationCode": "WS0124",
            "workStation": "1#注塑工作站",
            "workorderId": 27,
            "prodCode": "MO202504120013",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-04-12 00:00:00",
            "issueDate": "2025-04-12 21:15:10",
            "status": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "testuser",
            "create": "2025-04-12 18:36:00",
            "updateBy": "testuser",
            "update": "2025-04-12 18:39:56",
            "note": "",
            "params": {},
            "id": 8,
            "code": "ISSUE20250412005",
            "name": "123321",
            "workstationId": null,
            "workstationCode": null,
            "workStation": null,
            "workorderId": 27,
            "prodCode": "MO202504120013",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-04-12 18:35:52",
            "issueDate": "2025-04-12 18:35:46",
            "status": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "testuser",
            "create": "2025-04-12 18:25:35",
            "updateBy": "testuser",
            "update": "2025-04-13 19:36:42",
            "note": "",
            "params": {},
            "id": 7,
            "code": "ISSUE20250412004",
            "name": "11414",
            "workstationId": null,
            "workstationCode": null,
            "workStation": null,
            "workorderId": 27,
            "prodCode": "MO202504120013",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-04-12 18:25:24",
            "issueDate": "2025-04-12 18:25:17",
            "status": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "testuser",
            "create": "2025-04-12 15:11:43",
            "updateBy": "testuser",
            "update": "2025-04-12 21:10:14",
            "note": "",
            "params": {},
            "id": 6,
            "code": "ISSUE20250412003",
            "name": "2321",
            "workstationId": null,
            "workstationCode": null,
            "workStation": null,
            "workorderId": 10,
            "prodCode": "MO202503180007",
            "taskId": null,
            "taskCode": null,
            "clientId": 210,
            "clientCode": "C00201",
            "customerName": "小米",
            "clientNick": null,
            "time": "2025-04-12 15:11:28",
            "issueDate": "2025-04-12 15:11:18",
            "status": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "testuser",
            "create": "2025-04-12 14:44:38",
            "updateBy": "testuser",
            "update": "2025-04-12 15:02:41",
            "note": "",
            "params": {},
            "id": 5,
            "code": "ISSUE20250412001",
            "name": "111",
            "workstationId": null,
            "workstationCode": null,
            "workStation": null,
            "workorderId": 10,
            "prodCode": "MO202503180007",
            "taskId": null,
            "taskCode": null,
            "clientId": 210,
            "clientCode": "C00201",
            "customerName": "小米",
            "clientNick": null,
            "time": "2025-04-12 14:44:31",
            "issueDate": "2025-04-12 14:44:24",
            "status": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "admin",
            "create": "2025-03-17 18:31:58",
            "updateBy": "admin",
            "update": "2025-03-26 09:57:41",
            "note": "",
            "params": {},
            "id": 4,
            "code": "ISSUE20250317001",
            "name": "BOM外领料测试",
            "workstationId": 1,
            "workstationCode": "WS0124",
            "workStation": "1#注塑工作站",
            "workorderId": 2,
            "prodCode": "MO202503120009",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-03-25 00:00:00",
            "issueDate": "2025-03-17 18:31:39",
            "status": "todo",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "admin",
            "create": "2025-03-15 23:25:24",
            "updateBy": "admin",
            "update": "2025-03-15 23:26:19",
            "note": "",
            "params": {},
            "id": 3,
            "code": "ISSUE20250315003",
            "name": "包装领料",
            "workstationId": 14,
            "workstationCode": "WS0138",
            "workStation": "包装工作站",
            "workorderId": 1,
            "prodCode": "MO202503120008",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-03-31 00:00:00",
            "issueDate": "2025-03-15 23:25:06",
            "status": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "admin",
            "create": "2025-03-15 10:59:44",
            "updateBy": "admin",
            "update": "2025-03-15 11:00:31",
            "note": "",
            "params": {},
            "id": 2,
            "code": "ISSUE20250315002",
            "name": "机加工领料",
            "workstationId": null,
            "workstationCode": null,
            "workStation": null,
            "workorderId": 3,
            "prodCode": "MO202503120010",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-03-15 00:00:00",
            "issueDate": "2025-03-15 10:59:20",
            "status": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        },
        {
            "searchValue": null,
            "createBy": "admin",
            "create": "2025-03-12 16:23:16",
            "updateBy": "admin",
            "update": "2025-03-12 23:06:12",
            "note": "",
            "params": {},
            "id": 1,
            "code": "ISSUE20250312001",
            "name": "注塑生产领料",
            "workstationId": 1,
            "workstationCode": "WS0124",
            "workStation": "1#注塑工作站",
            "workorderId": 2,
            "prodCode": "MO202503120009",
            "taskId": null,
            "taskCode": null,
            "clientId": 207,
            "clientCode": "C00197",
            "customerName": "博世",
            "clientNick": null,
            "time": "2025-03-12 18:00:00",
            "issueDate": "2025-03-12 16:22:50",
            "status": "done",
            "attr1": null,
            "attr2": null,
            "attr3": 0,
            "attr4": 0
        }
    ]
    const defaultSubData = [
        {}
    ]
    const [mainData, setMainData] = React.useState(defaultMainData);
    const [subData, setSubData] = React.useState(defaultSubData);
    const [mainPostForm] = Form.useForm()
    const [mainUpdateForm] = Form.useForm()
    const [subPostForm] = Form.useForm()

    const defaultSearchKeys = 'code,name';
    let searchKeyList = defaultSearchKeys.split(',').map(item => item.trim());
    //console.log(supportExport)


    //Api方法区 两个get 两个post 一个put 还有一个实际改变库存的方法

    //getMainData
    function getMainData(url) {
        fetch(url)
            .then(response => response.json())
            .then(data => {
                setMainData(data.data);
            })
    }
    //getSubData 
    function getSubData(url) {
        fetch(url)
            .then(response => response.json())
            .then(data => {
                setSubData(data.data);
            })
    }
    //act 
    function act(url) {
        fetch(url)
            .then(response => response.json())
            .then(data => {
            })
        messageApi.open({
            type: 'success',
            content: '入库成功',
        });
    }
    //postMainData
    function postMainData(values: any, url) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '新增成功',
        });
    }
    //postMainData
    function postSubData(values: any, url) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '新增成功',
        });
    }
    //putMainData
    function putMainData(values: any, url) {
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(
                values
            )
        })
            .then(response => response.json())
            .then(data => {

            })
        messageApi.open({
            type: 'success',
            content: '修改成功',
        });
    }


    //筛选功能
    const handleSearch = () => {
        //这里的查找是字符串包含 如果要完全匹配改成===
        let filteredData = mainData;

        for (var i in searchKeyList) {
            var searchKey = searchKeyList[i];
            if (searchKey === 'id')
                continue;
            if (searchTerm[searchKey]) {
                filteredData = filteredData.filter(item => item[searchKey].includes(searchTerm[searchKey]));
            }
        }
        //console.log(filteredData)
        setMainData(filteredData);
    }
    const resetSearch = () => {
        setSearchTerm({})
        //TODO: setMainData()
    }
    const SearchInput = () => {
        const handleInputChange = (key) => (e) => {
            setSearchTerm(prevState => ({
                ...prevState,
                [key]: e.target.value
            }));
            console.log(key, e.target.value);
        }
        return (
            <>
                <Space size='large'>
                    {searchKeyList.map(key => (
                        <Input
                            placeholder={"请输入" + key}
                            value={searchTerm[key]}
                            onChange={handleInputChange(key)}
                            style={{ width: 200 }}
                        />
                    ))}
                </Space>
            </>
        )
    }

    //主界面表格列
    let mainColumns = []
    let mainColumnsJson = {

        "code": "领料单编号",
        "name": "领料单名称",
        "prodCode": "生产工单",
        "workStation": "工作站",
        "customerName": "客户名称",
        "time": "需求时间",
        "status": "状态",
        "action": "操作"
    }
    //数据项子界面表格列
    let subColumns = []
    let subColumnsJson = {
        "code": "物料编码",
        "name": "物料名称",
        "specification": "规格型号",
        "amount": "数量",
        "unit": "单位",
        "batchNumber": "批次号",
        "note": "备注"
    }
    for (var x in mainColumnsJson) {
        mainColumns.push({
            title: mainColumnsJson[x],
            dataIndex: x,
            key: x
        })
    }
    for (var x in subColumnsJson) {
        subColumns.push({
            title: subColumnsJson[x],
            dataIndex: x,
            key: x
        })
    }
    //自定义操作列渲染
    const targetObject = mainColumns.find(item => item.key === 'action');
    const edit = (record) => {
        mainUpdateForm.setFieldsValue(record);
        updateModalVisibility(1, true);
    }
    const deleteRow = (key) => {
        const newData = mainData.filter((item) => item.id !== key);
        setMainData(newData);

        //TODO Fetch DELETE
    };

    if (targetObject) {
        targetObject.render = (_, record) => {
            if (record.status === 'todo') {
                return (
                    <>
                        <Space size='middle'>
                            <a href="#" onClick={() => edit(record)}><PlayCircleOutlined /> 执行领出</a>
                            <Popconfirm title="确定要删除吗？" onConfirm={() => deleteRow(record.id)}>
                                <a href="#" style={{ color: 'red' }}><DeleteOutlined /> 删除</a>
                            </Popconfirm>
                        </Space>
                    </>
                )
            } else {
                return (<></>)
            }

        };
    }

    const statusObject = mainColumns.find(item => item.key === 'status');
    if (statusObject) {
        statusObject.render = (_, record) => {
            if (record.status === 'todo') {
                return (<>待领出</>)
            } else {
                return (<>已完成</>)
            }
        }
    }

    const codeObject = mainColumns.find(item => item.key === 'code');
    if (codeObject) {
        codeObject.render = (_, record) => {
            return (
                <>
                    <a href="#" onClick={() => edit(record)}>{record.code}</a>
                </>
            )
        }
    }

    //console.log('mainColumns: ', mainColumns);



    //对话框
    const [isModalVisible, setIsModalVisible] = React.useState([false, false, false]);

    // 修改第 i 个元素的值
    const updateModalVisibility = (i: number, newValue: boolean) => {
        setIsModalVisible(prevState => {
            // 创建一个新的数组，避免直接修改原数组
            const newArray = [...prevState];
            newArray[i] = newValue; // 修改第 i 个元素
            return newArray;
        });
    };
    const onFinish = (values: any) => {
        console.log('Success:', values);
        updateModalVisibility(0, false);
    };
    const submitMainUpdateForm = (values: any) => {
        console.log('Success:', values);
        updateModalVisibility(1, false);
    }

    const formItemsJsonA =
        [
            {
                gutter: 16,
                cols: [
                    {
                        span: 12,
                        label: '领料单编号',
                        name: 'code',
                        type: 'Input'
                    },
                    {
                        span: 12,
                        label: '领料单名称',
                        name: 'name',
                        type: 'Input',
                    }
                ]
            },
            {
                gutter: 16,
                cols: [
                    {
                        span: 8,
                        label: '需求日期',
                        name: 'time',
                        type: 'Input',
                    },
                    {
                        span: 8,
                        label: '生产工单',
                        name: 'prodCode',
                        type: 'Input',
                    },
                    {
                        span: 8,
                        label: '工作站',
                        name: 'workStation',
                        type: 'Input',
                    }
                ]
            },
            {
                cols: [
                    {
                        span: 12,
                        label: '备注',
                        name: 'note',
                        type: 'TextArea',
                        rows: 3
                    }
                ]
            }
        ]
    /**
* 根据 formItemsJson 生成 JSX 代码字符串（不包含 rules）
* @param {Array} formItemsJson - 表单项的 JSON 数据
* @returns {string} - 生成的 JSX 代码字符串
*/
    function generateJSXFromJSON(formItemsJson) {
        const jsxCode = [];

        formItemsJson.forEach((row, rowIndex) => {
            // 处理每一行
            const rowChildren = [];
            row.cols.forEach((col, colIndex) => {
                // 处理每一列
                const { type, name, label, span } = col;

                // 构建 <Form.Item> 的属性
                const formItemProps = [
                    `label="${label}"`,
                    `name="${name}"`,
                ];

                // 构建表单控件（如 Input、TextArea 等）
                let control;
                switch (type) {
                    case 'Input':
                        control = `<Input placeholder="${label}" />`;
                        break;
                    case 'TextArea':
                        control = `<Input.TextArea placeholder="${label}" rows={${col.rows || 3}} />`;
                        break;
                    case 'InputNumber':
                        control = `<InputNumber placeholder="${label}" />`;
                        break;
                    default:
                        control = '';
                }

                // 构建完整的 <Form.Item>
                const formItem = `<Form.Item ${formItemProps.join(' ')}>\n  ${control}\n</Form.Item>`;
                rowChildren.push(formItem);
            });

            // 将当前行的内容包裹在 <Row> 和 <Col> 中
            const rowContent = rowChildren.map((child) => `<Col span={${row.cols.span || 8}}>\n  ${child}\n</Col>`).join('\n');
            jsxCode.push(`<Row gutter={${row.gutter || 0}}>\n${rowContent}\n</Row>`);
        });

        // 返回最终的 JSX 代码
        return jsxCode.join('\n\n');
    }

    console.log(generateJSXFromJSON(formItemsJsonA));





    const CustomFormA = () => {
        const ret = (
            <>
                <Form form={mainPostForm} name='mainPostForm' onFinish={onFinish} layout="vertical" labelAlign='left'>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="领料单编号" name="code">
                                <Input placeholder="领料单编号" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="领料单名称" name="name">
                                <Input placeholder="领料单名称" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="需求日期" name="time">
                                <Input placeholder="需求日期" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="生产工单" name="prodCode">
                                <Input placeholder="生产工单" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="工作站" name="workStation">
                                <Input placeholder="工作站" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={0}>
                        <Col span={12}>
                            <Form.Item label="客户名称" name="customerName">
                                <Input placeholder="请输入客户名称" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="备注" name="note">
                                <Input.TextArea placeholder="请输入备注" rows={3} />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item>
                        <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                            <Button onClick={() => updateModalVisibility(0, false)}>取消</Button>
                            <Button type="primary" htmlType="submit" onClick={() => {
                                console.log(mainPostForm.getFieldValue('code'));
                            }}>提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </>
        )

        return ret;
    }

    const CustomFormB = () => {
        return (
            <>
                <Form form={subPostForm} name='subPostForm' onFinish={onFinish} layout="vertical" labelAlign='left'>
                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="物料编号" name="code">
                                <Input placeholder="物料编号" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="物料名称" name="name">
                                <Input placeholder="物料名称" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="单位" name="unit">
                                <Input placeholder="单位" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="入库数量" name="amount">
                                <InputNumber placeholder="入库数量" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="规格型号" name="specification">
                                <Input placeholder="规格型号" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="批次号" name="batchNumber">
                                <Input placeholder="批次号" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={0}>
                        <Col span={24}>
                            <Form.Item label="备注" name="note">
                                <Input.TextArea placeholder="请输入备注" rows={3} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Form.Item>
                        <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                            <Button onClick={() => updateModalVisibility(2, false)}>取消</Button>
                            <Button type="primary" htmlType="submit" onClick={() => {
                                updateModalVisibility(2, false)
                            }}>提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </>
        )
    }

    const CustomFormWithTable = () => {
        return (
            <>
                <Form form={mainUpdateForm} name="mainUpdateForm" onFinish={submitMainUpdateForm} layout="vertical" labelAlign='left'>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item label="领料单编号" name="code">
                                <Input placeholder="领料单编号" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="领料单名称" name="name">
                                <Input placeholder="领料单名称" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={16}>
                        <Col span={8}>
                            <Form.Item label="需求日期" name="time">
                                <Input placeholder="需求日期" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="生产工单" name="prodCode">
                                <Input placeholder="生产工单" />
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="工作站" name="workStation">
                                <Input placeholder="工作站" />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Row gutter={0}>
                        <Col span={12}>
                            <Form.Item label="客户名称" name="customerName">
                                <Input placeholder="请输入客户名称" />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label="备注" name="note">
                                <Input.TextArea placeholder="请输入备注" rows={3} />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Divider>物料信息</Divider>
                    <Card extra={<Button type="primary" onClick={() => updateModalVisibility(2, true)}>新增</Button>}>
                        <Table columns={subColumns} dataSource={subData}></Table>
                    </Card>


                    <Form.Item>
                        <Space style={{ marginLeft: 400, marginTop: 16 }} direction="horizontal">
                            <Button onClick={() => updateModalVisibility(1, false)}>取消</Button>
                            <Button type="primary" htmlType="submit" >提交</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </>
        )
    }

    return (
        <>
            {contextHolder}

            <div style={{ marginTop: 20, marginLeft: 20 }}>
                <Space size='large'>
                    <SearchInput />
                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                        搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={resetSearch}>
                        重置
                    </Button>
                    <Button type="primary" onClick={() => updateModalVisibility(0, true)}>
                        + 新增
                    </Button>
                    {/* 主界面新增对话框 一个Form*/}
                    <MyModal open={isModalVisible[0]} onCancel={() => updateModalVisibility(0, false)}>
                        <CustomFormA />
                    </MyModal>
                    {/* 主界面更新对话框 包括一个Form和一个Table */}
                    <MyModal open={isModalVisible[1]} onCancel={() => updateModalVisibility(1, false)}>
                        <CustomFormWithTable />
                    </MyModal>
                    {/* 子界面新增对话框 一个Form*/}
                    <MyModal open={isModalVisible[2]} onCancel={() => updateModalVisibility(2, false)} >
                        <CustomFormB />
                    </MyModal>
                </Space>
                <Divider />
                <Row>
                    <Table dataSource={mainData} columns={mainColumns} style={{ width: '100%' }}></Table>
                </Row>
            </div>
        </>
    )

}

Picking.displayName = '生产入料'
export default Picking;